package com.grain.security.rbac.repository.support;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

import java.util.ArrayList;
import java.util.List;

public class QueryResultConverter {
    private static Logger logger = LoggerFactory.getLogger(QueryResultConverter.class);

    public static <T, I> Page<I> convert(Page<T> pageData, Class<I> clazz, Pageable pageable) {
        List<T> contents = pageData.getContent();
        List<I> infos = convert(contents, clazz);
        return new PageImpl<I>(infos, pageable, pageData.getTotalElements());
    }

    public static <I, T> List<I> convert(List<T> contents, Class<I> clazz) {
        List<I> infos = new ArrayList<>();
        for (T content : contents) {
            I info = null;
            try {
                info = clazz.newInstance();
            } catch (Exception e) {
                logger.info("转换数据失败", e);
                throw new RuntimeException("数据转换失败");
            }
            if (info != null) {
                infos.add(info);
            }

        }
        return infos;
    }

    public static <I, T> Page<I> convert(Page<T> pageData, Pageable pageable, Domain2InfoConverter<T, I> converter) {
        List<T> contents = pageData.getContent();
        List<I> infos = converter(contents, converter);
        return new PageImpl<I>(infos,pageable,pageData.getTotalElements());
    }

    public static <I, T> List<I> converter(List<T> contents, Domain2InfoConverter<T, I> converter) {
        List<I> infos = new ArrayList<>();
        for (T content : contents) {
            infos.add(converter.convert(content));
        }
        return infos;
    }
}
